<?php

namespace app\admin\controller\choi;

use app\admin\model\choi\CourseOrder as CourseOrderModel;
use app\api\model\Teacher as TeacherModel;
use app\common\model\TeacherMoneyLog as TeacherMoneyLogModel;
use app\api\service\CourseRemindService;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\choi\TeacherCourse as TeacherCourseModel;

/**
 * 课表管理
 *
 * @icon fa fa-circle-o
 */
class Course extends Backend
{
    
    /**
     * Course模型对象
     * @var \app\admin\model\choi\Course
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\choi\Course;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['courseOrder', 'teacher', 'user'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['courseOrder', 'teacher', 'user'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $time = explode('-', $row['time']);
        $row['starttime'] = trim($time[0] ?? '');
        $row['endtime'] = trim($time[1] ?? '');
        $hour = TeacherCourseModel::getHour($row['teacher_course_id']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['time'] = $params['starttime'].'-'.$params['endtime'];
                $params['week'] = getWeek($params['date']);
                $starttime = explode(':', $params['starttime']);
                $endtime = explode(':', $params['endtime']);
                if (isset($params['status'])) {
                    if ($params['status'] == 2) {
                        $params['date'] = '';
                        $params['time'] = '';
                        $params['week'] = '';
                    } else {
                        if (str_replace(':', '', $params['endtime']) <= str_replace(':', '', $params['starttime'])) {
                            $this->error('结束时间必须大于开始时间');
                        }
                        if ($starttime[0] + $hour != $endtime[0] || $starttime[0] + $hour . $starttime[1] != str_replace(':', '', $params['endtime'])) {
                            $this->error('开始、结束时间区间应为'.$hour.'小时');
                        }
                        $course = $this->model->where('status', 3)->where('date', $params['date'])->where('time', $params['time'])->find();
                        if ($course && $course->course_id != $ids) {
                            $this->error('该时间以被预约，请更换其他时间');
                        }
                    }
                }



                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if (isset($params['status']) && $params['status'] == 4) {
                        //是否全部完成
                        $courseCount = $this->model->where('course_order_id', $row['course_order_id'])->where('status', 4)->count();
                        $courseOrder = CourseOrderModel::find($row['course_order_id']);
                        if ($courseOrder && $courseCount == $courseOrder->num) {
                            //更新订单完成
                            $courseOrder->status = 3;
                            $courseOrder->save();
                            //教师
                            $teacher = TeacherModel::find($courseOrder->teacher_id);
                            if ($teacher) {
                                //记录教师账号明细
                                $res = TeacherMoneyLogModel::add($teacher, $courseOrder->total_price, 1, $courseOrder->course_order_id);
                                //教师获得课程费
                                $teacher->setInc('money', $courseOrder->total_price);
                            }
                        }
                        //课程提醒
                        CourseRemindService::courseRemind($row['course_id'], 2, true);
                    }


                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        $this->assign('statusList', $this->model->getStatus());
        $this->assign('times', $this->times());
        $this->assign('hour', $hour ?: 1);
        return $this->view->fetch();
    }

    /**
     * 时间段
     */
    private function times()
    {
        return [
            '06:00', '06:30', '07:00', '07:30', '08:00', '08:30',
            '09:00', '09:30', '10:00', '10:30', '11:00', '11:30',
            '12:00', '12:30', '13:00', '13:30', '14:00', '14:30',
            '15:00', '15:30', '16:00', '16:30', '17:00', '17:30',
            '18:00', '18:30', '19:00', '19:30', '20:00', '20:30',
            '21:00', '21:30', '22:00', '22:30', '23:00', '23:30',
            '24:00'
        ];
    }

}
